package com.zzyk.main.mqtt;

import com.alibaba.fastjson.JSON;
import com.zzyk.main.mapper.ConnectionMapper;
import com.zzyk.main.utils.BeanContext;
import com.zzyk.main.utils.RedisUtils;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;


public class PushCallback extends MyMqttClient implements MqttCallback {

    private ConnectionMapper connectionMapper;
    private RedisUtils redisUtils;

    {
        this.connectionMapper = BeanContext.getApplicationContext().getBean(ConnectionMapper.class);
        this.redisUtils = BeanContext.getApplicationContext().getBean(RedisUtils.class);
    }

    @Override
    public void connectionLost(Throwable cause) {
        System.out.println("connectionLost---------连接断开，可以做重连");
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        try {
            System.out.println("接收消息主题 : " + topic);
            System.out.println("接收消息Qos : " + message.getQos());
            String res = new String(message.getPayload());
            if (res.length() < 20) {
                return;
            }
            System.out.println("接收消息内容 : " + res);
             JSON.parseObject(res);
            redisUtils.set(topic + "_conf", res, 250);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
